<template>
  <div class="review-list-container">
    <el-card shadow="hover">
      <div slot="header" class="card-header">
        <span class="header-title">
          <i class="el-icon-chat-line-square"></i>
          我的评价
        </span>
      </div>

      <!-- 评价列表 -->
      <div class="review-list">
        <div v-for="review in reviewList" :key="review.id" class="review-card">
          <!-- 商品信息 -->
          <div class="product-section">
            <img 
              :src="review.productImage" 
              :alt="review.productName" 
              class="product-image">
            <div class="product-info">
              <div class="product-name">{{ review.productName }}</div>
              <div class="order-info">
                <span>订单编号：{{ review.orderNo }}</span>
                <span class="create-time">{{ formatDate(review.createTime) }}</span>
              </div>
            </div>
          </div>

          <!-- 评价内容 -->
          <div class="review-content-section">
            <div class="rating-display">
              <el-rate 
                v-model="review.rating" 
                disabled 
                show-score 
                text-color="#ff9900">
              </el-rate>
            </div>
            <div class="review-text">{{ review.content }}</div>
          </div>

          <!-- 操作按钮 -->
          <div class="action-buttons">
            <el-button 
              type="primary" 
              size="small" 
              plain
              @click="handleEditReview(review)">
              修改评价
            </el-button>
            <el-button 
              type="danger" 
              size="small" 
              plain
              @click="handleDeleteReview(review.id)">
              删除评价
            </el-button>
          </div>
        </div>

        <!-- 空状态 -->
        <el-empty v-if="reviewList.length === 0" description="暂无评价">
          <el-button type="primary" @click="goToOrderList">去看看我的订单</el-button>
        </el-empty>
      </div>

      <!-- 分页 -->
      <div class="pagination-container" v-if="total > 0">
        <el-pagination
          background
          layout="total, prev, pager, next, sizes"
          :current-page="currentPage"
          :page-size="pageSize"
          :page-sizes="[10, 20, 30, 50]"
          :total="total"
          @current-change="handlePageChange"
          @size-change="handleSizeChange">
        </el-pagination>
      </div>
    </el-card>

    <!-- 修改评价弹窗 -->
    <el-dialog 
      title="修改评价" 
      :visible.sync="editDialogVisible" 
      width="600px"
      @close="resetEditForm">
      <el-form :model="editForm" :rules="editRules" ref="editForm" label-width="80px">
        <el-form-item label="商品名称">
          <div class="product-name-display">{{ editForm.productName }}</div>
        </el-form-item>
        <el-form-item label="评分" prop="rating">
          <el-rate 
            v-model="editForm.rating" 
            show-text 
            :texts="['极差', '失望', '一般', '满意', '惊喜']">
          </el-rate>
        </el-form-item>
        <el-form-item label="评价内容" prop="content">
          <el-input 
            type="textarea" 
            v-model="editForm.content" 
            :rows="6" 
            placeholder="请输入您的评价内容，分享您的使用感受..."
            maxlength="500"
            show-word-limit>
          </el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="editDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="submitEditReview">提交修改</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import { getUserReviewList, updateReview, deleteReview } from '@/api/review';

export default {
  name: 'UserReviewList',
  data() {
    return {
      reviewList: [],
      currentPage: 1,
      pageSize: 10,
      total: 0,
      loading: false,
      editDialogVisible: false,
      editForm: {
        reviewId: null,
        productName: '',
        rating: 5,
        content: ''
      },
      editRules: {
        rating: [
          { required: true, message: '请选择评分', trigger: 'change' }
        ],
        content: [
          { required: true, message: '请输入评价内容', trigger: 'blur' },
          { min: 5, max: 500, message: '评价内容长度在 5 到 500 个字符', trigger: 'blur' }
        ]
      }
    };
  },
  created() {
    this.loadReviewList();
  },
  methods: {
    // 加载评价列表
    async loadReviewList() {
      this.loading = true;
      try {
        const userInfo = JSON.parse(localStorage.getItem('userInfo'));
        if (!userInfo) {
          this.$router.push('/login');
          return;
        }

        const response = await getUserReviewList(
          userInfo.id, 
          this.currentPage, 
          this.pageSize
        );

        if (response.data.success) {
          this.reviewList = response.data.data.records || [];
          this.total = response.data.data.total || 0;
        } else {
          this.$notify({
            title: '失败',
            message: response.data.message || '加载评价失败',
            type: 'error',
            duration: 2000
          });
        }
      } catch (error) {
        this.$notify({
          title: '错误',
          message: '加载评价失败，请稍后重试',
          type: 'error',
          duration: 2000
        });
      } finally {
        this.loading = false;
      }
    },

    // 格式化日期
    formatDate(date) {
      if (!date) return '';
      const d = new Date(date);
      const year = d.getFullYear();
      const month = String(d.getMonth() + 1).padStart(2, '0');
      const day = String(d.getDate()).padStart(2, '0');
      const hours = String(d.getHours()).padStart(2, '0');
      const minutes = String(d.getMinutes()).padStart(2, '0');
      return `${year}-${month}-${day} ${hours}:${minutes}`;
    },

    // 打开修改评价弹窗
    handleEditReview(review) {
      this.editForm.reviewId = review.id;
      this.editForm.productName = review.productName;
      this.editForm.rating = review.rating;
      this.editForm.content = review.content;
      this.editDialogVisible = true;
    },

    // 提交修改评价
    submitEditReview() {
      this.$refs.editForm.validate(async (valid) => {
        if (valid) {
          try {
            const userInfo = JSON.parse(localStorage.getItem('userInfo'));
            const response = await updateReview({
              reviewId: this.editForm.reviewId,
              userId: userInfo.id,
              content: this.editForm.content,
              rating: this.editForm.rating
            });

            if (response.data.success) {
              this.$notify({
                title: '成功',
                message: '评价修改成功',
                type: 'success',
                duration: 2000
              });
              this.editDialogVisible = false;
              this.loadReviewList();
            } else {
              this.$notify({
                title: '失败',
                message: response.data.message || '修改评价失败',
                type: 'error',
                duration: 2000
              });
            }
          } catch (error) {
            this.$notify({
              title: '错误',
              message: '修改评价失败，请稍后重试',
              type: 'error',
              duration: 2000
            });
          }
        }
      });
    },

    // 删除评价
    handleDeleteReview(reviewId) {
      this.$confirm('确定要删除该评价吗？删除后将无法恢复。', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {
        try {
          const userInfo = JSON.parse(localStorage.getItem('userInfo'));
          const response = await deleteReview({
            reviewId: reviewId,
            userId: userInfo.id
          });

          if (response.data.success) {
            this.$notify({
              title: '成功',
              message: '评价已删除',
              type: 'success',
              duration: 2000
            });
            this.loadReviewList();
          } else {
            this.$notify({
              title: '失败',
              message: response.data.message || '删除评价失败',
              type: 'error',
              duration: 2000
            });
          }
        } catch (error) {
          this.$notify({
            title: '错误',
            message: '删除评价失败，请稍后重试',
            type: 'error',
            duration: 2000
          });
        }
      }).catch(() => {});
    },

    // 重置修改表单
    resetEditForm() {
      this.$refs.editForm.resetFields();
      this.editForm = {
        reviewId: null,
        productName: '',
        rating: 5,
        content: ''
      };
    },

    // 跳转到订单列表
    goToOrderList() {
      this.$router.push('/user/order-list');
    },

    // 页码变化
    handlePageChange(page) {
      this.currentPage = page;
      this.loadReviewList();
    },

    // 每页大小变化
    handleSizeChange(size) {
      this.pageSize = size;
      this.currentPage = 1;
      this.loadReviewList();
    }
  }
};
</script>

<style scoped>
.review-list-container {
  min-height: calc(100vh - 130px);
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.header-title {
  font-size: 18px;
  font-weight: 600;
  color: #303133;
}

.header-title i {
  font-size: 20px;
  margin-right: 8px;
  color: #2c5f2d;
}

/* 评价列表 */
.review-list {
  display: flex;
  flex-direction: column;
  gap: 20px;
}

/* 评价卡片 */
.review-card {
  border: 1px solid #e4e7ed;
  border-radius: 8px;
  padding: 20px;
  transition: all 0.3s;
}

.review-card:hover {
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
}

/* 商品信息区 */
.product-section {
  display: flex;
  gap: 15px;
  padding-bottom: 15px;
  border-bottom: 1px solid #e4e7ed;
  margin-bottom: 15px;
}

.product-image {
  width: 80px;
  height: 80px;
  border-radius: 8px;
  object-fit: cover;
  flex-shrink: 0;
  border: 1px solid #e4e7ed;
}

.product-info {
  flex: 1;
  display: flex;
  flex-direction: column;
  justify-content: center;
  gap: 8px;
}

.product-name {
  font-size: 15px;
  font-weight: 600;
  color: #303133;
}

.order-info {
  display: flex;
  justify-content: space-between;
  font-size: 13px;
  color: #909399;
}

.create-time {
  color: #b0b3b8;
}

/* 评价内容区 */
.review-content-section {
  margin-bottom: 15px;
}

.rating-display {
  margin-bottom: 10px;
}

.review-text {
  font-size: 14px;
  color: #606266;
  line-height: 1.6;
  padding: 12px;
  background: #f5f7fa;
  border-radius: 6px;
}

/* 操作按钮 */
.action-buttons {
  display: flex;
  gap: 10px;
  justify-content: flex-end;
}

/* 分页 */
.pagination-container {
  display: flex;
  justify-content: center;
  margin-top: 30px;
  padding-top: 20px;
  border-top: 1px solid #e4e7ed;
}

/* 弹窗 */
.product-name-display {
  font-size: 15px;
  color: #303133;
  font-weight: 600;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .product-section {
    flex-direction: column;
  }

  .product-image {
    width: 100%;
    height: auto;
  }

  .action-buttons {
    flex-direction: column;
  }
}
</style>

